package avicit.bdp.dds.server.master.processor;

import avicit.bdp.common.utils.SpringApplicationContext;
import avicit.bdp.common.utils.redis.RedisCacheHelper;
import avicit.bdp.dds.dispatch.enums.ExecutionStatus;
import avicit.bdp.dds.common.utils.Preconditions;
import avicit.bdp.dds.dao.entity.ProcessInstance;
import avicit.bdp.dds.dao.entity.TaskInstance;
import avicit.bdp.dds.remote.command.Command;
import avicit.bdp.dds.remote.command.CommandType;
import avicit.bdp.dds.remote.command.TaskKillResponseCommand;
import avicit.bdp.dds.remote.processor.NettyRequestProcessor;
import avicit.bdp.dds.remote.utils.FastJsonSerializer;
import avicit.bdp.dds.service.process.ProcessService;
import com.alibaba.fastjson2.JSON;
import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * task response processor
 */
public class TaskKillResponseProcessor implements NettyRequestProcessor {

    private final Logger logger = LoggerFactory.getLogger(TaskKillResponseProcessor.class);

    /**
     * processService
     */
    private final ProcessService processService = SpringApplicationContext.getBean(ProcessService.class);

    /**
     * task final result response
     * need master process , state persistence
     *
     * @param channel channel
     * @param command command
     */
    @Override
    public void process(Channel channel, Command command) {
        Preconditions.checkArgument(CommandType.TASK_KILL_RESPONSE == command.getType(), String.format("invalid command type : %s", command.getType()));

        TaskKillResponseCommand responseCommand = FastJsonSerializer.deserialize(command.getBody(), TaskKillResponseCommand.class);
        logger.info("received task kill response command : {}", responseCommand);

        String taskStr = RedisCacheHelper.getInstance().get("bdp:dds:task:" + responseCommand.getTaskInstanceId());
        //缓存信息是sparkFlow的虚拟节点
        if (StringUtils.isNotBlank(taskStr)) {
            TaskInstance taskInstance = JSON.parseObject(taskStr, TaskInstance.class);
            ProcessInstance instance = new ProcessInstance();
            instance.setState(ExecutionStatus.STOP.getCode());
            instance.setEndTime(new Date());
            instance.setId(taskInstance.getProcessInstanceId());
            processService.updateProcessInstanceByPrimaryKeySelective(instance);
            return;
        }

        TaskInstance taskInstance = processService.findTaskInstanceById(responseCommand.getTaskInstanceId());
        //如果sparkFlow 则taskInstance is null
        if (taskInstance == null) {
            return;
        }
        taskInstance.setState(ExecutionStatus.STOP.getCode());
        taskInstance.setPid(responseCommand.getProcessId());
        taskInstance.setAppLink(JSON.toJSONString(responseCommand.getAppIds()));
        processService.updateTaskInstance(taskInstance);
        logger.info("received task kill, update task instance [{}] end", responseCommand.getTaskInstanceId());
    }

}
